<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use Exception;
use fast\Random;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 渠道分销商
 *
 * @icon fa fa-circle-o
 */
class Distributor extends Backend
{

    /**
     * Distributor模型对象
     * @var \app\common\model\Distributor
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Distributor;
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    /**
     * 验证
     * */
    protected function check($params,$id=0){
        if(!empty($id)){
            $data=[
                ['name', 'require', '服务商名称不能为空'],
                ['password', 'regex:\S{6,30}', '密码长度必须在6-30位之间，不能包含空格'],
                ['mobile', 'require|regex:/^1\d{10}$/|unique:distributor,mobile,'.$id, '手机号码（账号）不能为空|手机号码（账号）格式错误|手机号码（账号）已存在'],
            ];
        }else{
            $data=[
                ['name', 'require', '服务商名称不能为空'],
                ['password', 'require|regex:\S{6,30}', '密码不能为空|密码长度必须在6-30位之间，不能包含空格'],
                ['mobile', 'require|regex:/^1\d{10}$/|unique:distributor,mobile', '手机号码（账号）不能为空|手机号码（账号）格式错误|手机号码（账号）已存在'],
            ];
        }
        $validate = new \think\Validate($data);
        if (!$validate->check($params)) {
            $this->error('提交失败：' . $validate->getError());
        }
        return true;
    }
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        $res=$this->check($params);
        if(!$res) return $res;
        Db::startTrans();
        try {
            $params['salt'] = Random::alnum();
            $params['password'] = md5(md5($params['password']) . $params['salt']);
            $params["status"]='1';
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        $res=$this->check($params,$ids);
        if(!$res) return $res;
        Db::startTrans();
        try {
            if ($params['password']) {
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
            } else {
                unset($params['password'], $params['salt']);
            }
            if($params["status"]==1) $param["remark"]='';
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    /**
     * 审核
     * */
    public function operation($id = null){
        $param=$this->request->param();
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($param["status"]==1) $param["remark"]='';
        $result = $row->allowField(true)->save($param);
        if ($result !== false) {
            $this->success();
        } else {
            $this->error(__('No rows were updated'));
        }
    }


    /**
     * 查看详情
     * */
    public function see($id)
    {
        $row = $this->model->get($id);
        $this->assign("row",$row);
        return $this->view->fetch();
    }
}
